package com.example.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.config.handler.login.User;
import com.example.dao.MdlUserDao;
import com.example.config.handler.login.ClientUserDetails;
import com.example.entity.MdlUserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Set;

@Service
public class UserService {

  @Autowired
  private PasswordEncoder passwordEncoder;

  @Autowired
  private MdlUserDao mdlUserDao;

  public ClientUserDetails getUserByPhone(String phone) {
    LambdaQueryWrapper<MdlUserEntity> query = new LambdaQueryWrapper<>();
    query.eq(MdlUserEntity::getPhone, phone);
    MdlUserEntity mdlUserEntity = mdlUserDao.selectOne(query);
    if (mdlUserEntity == null) {
      return null;
    }
    ClientUserDetails clientUserDetails = new ClientUserDetails();
    clientUserDetails.setUsername(mdlUserEntity.getUsername());
    clientUserDetails.setPassword(mdlUserEntity.getPassword());
    clientUserDetails.setEnabled(mdlUserEntity.getIsActive().equals(1));
    clientUserDetails.setAuthorities(Set.of("sys.mdluser.page", "sys.mdluser.delete"));
    return clientUserDetails;
  }

  public ClientUserDetails getUserFromDB(String username) {
    LambdaQueryWrapper<MdlUserEntity> query = new LambdaQueryWrapper<>();
    query.eq(MdlUserEntity::getUsername, username);
    MdlUserEntity mdlUserEntity = mdlUserDao.selectOne(query);
    if (mdlUserEntity == null) {
      return null;
    }
    ClientUserDetails clientUserDetails = new ClientUserDetails();
    clientUserDetails.setUsername(mdlUserEntity.getUsername());
    clientUserDetails.setPassword(mdlUserEntity.getPassword());
    clientUserDetails.setEnabled(mdlUserEntity.getIsActive().equals(1));
    clientUserDetails.setAuthorities(Set.of("sys.mdluser.page", "sys.mdluser.delete"));
    return clientUserDetails;
  }

}
